package br.com.k19.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

public class HibernateDAO<T> implements InterfaceDAO<T> {

	private EntityManager manager;
	private Class<T> classe;

	public HibernateDAO(EntityManager manager, Class<T> classe) {
		this.manager = manager;
		this.classe = classe;
	}

	@Override
	public T busca(Integer id) {
		return manager.find(classe, id);
	}

	@Override
	public T altera(T bean) {
		return manager.merge(bean);
	}

	@Override
	public void adiciona(T bean) {
		manager.persist(bean);
	}

	@Override
	public void remove(Integer id) {
		T t = manager.find(classe, id);
		manager.remove(t);
	}

	@Override
	public List<T> lista() {
		String sql = "SELECT t FROM " + classe.getSimpleName() + " t";
		TypedQuery<T> query = manager.createQuery(sql, classe);
		return query.getResultList();
	}

	public void setManager(EntityManager manager) {
		this.manager = manager;
	}
}
